import router, { asyncRoutes } from './router'
import store from '@/store'
// 引入进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 引入修改标题
import getPageTitle from '@/utils/get-page-title'
// 定义一个白名单
const whiltList = ['/login', '/404']

// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 获取 token
  const token = store.getters.token
  if (token) { // 已登录
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
      if (!store.getters.name) {
        await store.dispatch('user/getuserInfoAction')
      }
      if (!store.getters.isHaveAsyncRoute) {
        store.commit('app/SET_ASYNCROUTE') // 修改状态,已经挂载
        const menusArr = store.getters.menus // 路由标识数组
        const asyncRoutesArr = asyncRoutes.filter(item => {
          return menusArr.includes(item.children[0].name.toLowerCase())
        })
        router.addRoutes(asyncRoutesArr)
        store.commit('permission/setRoutes', asyncRoutesArr)
      }
    }
  } else { // 未登录
    if (whiltList.includes(to.path)) next()
    else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // 关闭进度条
  NProgress.done()
  document.title = getPageTitle(to.meta.title)
})
